﻿using Blm.RabbitMQ.MessageQueue;
using Blm.Utils.Extensions;
using Blm.Utils.Utility;
using ExcelReport;
using ExcelReport.Driver.NPOI;
using ExcelReport.Renderers;
using Language.Resource;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.Configs;
using VisionCloud.Domain.DtoModel.RabbitMq;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Repository.Implement.Sys;
using VisionCloud.Domain.Repository.Interface.Sys;
using VisionCloud.Domain.UnitOfWork;
using VisionCloud.Utility;
using VisionCloud.Utility.Option;
using AjaxCode = VisionCloud.Domain.Common.AjaxCode;

namespace VisionCloud.Service.Sys
{
    public class SysDeviceService
    {
        public IUnitOfWork UnitOfWork { get; set; }
        public ILogger<SysDeviceService> Logger { get; set; }

        public ISysDeviceRepository SysDeviceRepository { get; set; }

        public ISysUserRepository userRepository { get; set; }

        public ISysUserUpdateRecordRepository UserUpdateRecordRepository { get; set; }

        /// <summary>
        /// 多语言资源类
        /// </summary>
        public IStringLocalizer<ServiceResource> ServiceLocalizer { get; set; }

        public IRabbitMQProducer RabbitMQProducer { get; set; }

        private UploadFileOptions uploadFileOptions;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="option"></param>
        public SysDeviceService(IOptionsMonitor<UploadFileOptions> option)
        {
            uploadFileOptions = option.CurrentValue;
        }

        /// <summary>
        /// 通过加密狗获取设备
        /// </summary>
        /// <param name="encryptedDogNumber">加密狗编号</param>
        /// <param name="encryptedDogType">加密狗类型</param>
        /// <returns></returns>
        public async Task<SysDevice> GetDeviceByencryptedDog(string encryptedDogNumber, string encryptedDogType)
        {
            return await SysDeviceRepository.FirstOrDefaultAsync(i =>
                i.EncryptedDogNumber == encryptedDogNumber && i.EncryptedDogType == encryptedDogType);
        }

        /// <summary>
        /// 获取设备列表信息
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<ApiPageResult> GetList(SearcheParaSysDevicePage condition)
        {
            if (!string.IsNullOrEmpty(condition.KeyWord))
            {
                if (condition.KeyWord.Length > 50)
                {
                    throw new OperationException(ServiceLocalizer["YB0284"].Value);
                }
            }
            return await SysDeviceRepository.GetSysDeviceNoDelete(condition);
        }

        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="deives"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeletesAsync(Guid[] deives)
        {
            return await SysDeviceRepository.DeletesAsync(deives);
        }

        /// <summary>
        /// 获取设备信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetDeviceByScannerSN(DeviceCondtion query)
        {
            var result = await SysDeviceRepository.GetModel(query);
            if (result == null)
            {
                return ApiResult.Success(ServiceLocalizer["YB0285"].Value);
            }
            return ApiResult.Success().SetData(result);
        }

        /// <summary>
        /// 分配设备给用户(批量)
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        public async Task<ApiResult> AssignDeviceUserBatch(AssignSysDeviceDto deviceInfo)
        {
            if (!string.IsNullOrEmpty(deviceInfo.DeviceUserId))
            {
                var user = userRepository.Single(d => d.YunUserGuid == deviceInfo.DeviceUserId.ToGuid());
                if (user == null || user.Name != deviceInfo.DeviceUserName)
                    return new ApiResult() { Code = AjaxCode.Error, Message = ServiceLocalizer["YB0257"].Value };

                var deviceList = await SysDeviceRepository.WhereAsync(d => d.DeviceUserId == deviceInfo.DeviceUserId.ToGuid());
                List<string> addDeviceList = new List<string>();
                List<string> deleteDeviceList = new List<string>();
                //获取需要添加的设备
                foreach (string id in deviceInfo.DeviceGuids)
                {
                    if (!deviceList.Any(d => d.DeviceGuid == id.ToGuid()))
                        addDeviceList.Add(id);
                }
                //获取需要删除的设备
                List<string> tl = new List<string>();
                tl.AddRange(deviceInfo.DeviceGuids.Select(it => it.ToLower()));
                foreach (var device in deviceList)
                {
                    if (!tl.Contains(device.DeviceGuid.ToString().ToLower()))
                        deleteDeviceList.Add(device.DeviceGuid.ToString());
                }
                bool ok1 = true, ok2 = true;
                if (addDeviceList.Count > 0)
                {
                    var result = await AssignDeviceUser(new AssignSysDeviceDto() { DeviceGuids = addDeviceList, DeviceUserId = deviceInfo.DeviceUserId, DeviceUserName = deviceInfo.DeviceUserName });
                    if (result.Code != AjaxCode.Success)
                        ok1 = false;
                }
                if (deleteDeviceList.Count > 0 && ok1)
                {
                    var result = await DeleteDeviceUser(new AssignSysDeviceDto() { DeviceGuids = deleteDeviceList, DeviceUserId = deviceInfo.DeviceUserId, DeviceUserName = deviceInfo.DeviceUserName });
                    if (result.Code != AjaxCode.Success)
                        ok2 = false;
                }
                if (ok1 && ok2)
                    return new ApiResult(AjaxCode.Success, "OK");
                return new ApiResult(AjaxCode.Fail, ServiceLocalizer["YB0286"].Value);
            }
            return new ApiResult { Code = AjaxCode.Error, Message = ServiceLocalizer["YB0247"].Value };
        }

        /// <summary>
        /// 分配设备给用户
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        public async Task<ApiResult> AssignDeviceUser(AssignSysDeviceDto deviceInfo)
        {
            deviceInfo.CurUserOrgId = OperatorProvider.Get().CompanyGuid.NullToString();
            return await SysDeviceRepository.AssignDeviceUser(deviceInfo);
        }

        /// <summary>
        /// 取消分配设备给用户
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteDeviceUser(AssignSysDeviceDto deviceInfo)
        {
            return await SysDeviceRepository.DeleteDeviceUser(deviceInfo);
        }

        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddDevice(SysDevice deviceInfo)
        {
            return await SysDeviceRepository.AddDevice(deviceInfo);
        }

        /// <summary>
        /// 更新设备
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateDevice(SysDevice device)
        {
            return await SysDeviceRepository.UpdateDevice(device);
        }

        /// <summary>
        /// 更新版本信息
        /// </summary>
        /// <param name="versionDto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateSoftVersion(SysDeviceVersionDto versionDto)
        {
            //Utility.Logger.Info("更新设备信息：" + JsonConvert.SerializeObject(versionDto));
            var result = await SysDeviceRepository.UpdateDeviceVersion(versionDto);
            var userId = OperatorProvider.Get().YunUserGuid;
            // 检查是否有更新权限
            var record = UserUpdateRecordRepository.GetLastRecordForUser(userId);
            if (record == null || userId != versionDto.UserId)
            {
                result = false;
                //Logger.LogWarning($"升级设备用户与更新用户可能不同一个人，操作userId：{userId}，参数userId:{versionDto.UserId}");
            }
            else
            {
                if (record != null)
                {
                    record.DeviceVersion = versionDto.SoftVersion;
                    record.DeviceMac = versionDto.DeviceMac;
                    record.LastUpdatedDate = DateTime.Now;
                    record.LastUpdatedBy = userId;
                    record.IsUpdated = true;
                    UserUpdateRecordRepository.Update(record);
                }
            }
            await UnitOfWork.SaveChangesAsync();
            return new ApiResult
            {
                Code = AjaxCode.Success,
                Result = result
            };
        }

        /// <summary>
        /// 生成三位随机数
        /// </summary>
        /// <returns></returns>
        private string GetRandomNumber()
        {
            Random ro = new Random();
            int iResult;
            int iUp = 9999;
            int iDown = 0000;
            iResult = ro.Next(iDown, iUp);
            return iResult.ToString().Trim();
        }

        /// <summary>
        /// 设备导出为excel
        /// </summary>
        /// <param name="deviceDtos"></param>
        /// <returns></returns>
        public async Task<string> ExportExcelFile(List<SysDeviceDto> deviceDtos)
        {
            // 准备模板路径和excel导出路径

            var excelPath = Path.Combine(uploadFileOptions.ParentDir, uploadFileOptions.TemporaryFiles);
            if (!Directory.Exists(excelPath)) Directory.CreateDirectory(excelPath);
            excelPath = Path.Combine(excelPath, deviceDtos[0].CustomerCompanyName + ServiceLocalizer["YB0441"].Value + DateTime.Now.ToString("yyyyMMddHHmmss") + $"_{GetRandomNumber()}.xlsx");
            var lang = CultureInfo.CurrentUICulture.Name;
            var templatePath = Path.Combine(uploadFileOptions.ParentDir, "SystemFiles/ExcelTemplates", $"设备信息批量导出模板-{lang}.xlsx");

            #region 生成EXCEL

            Configurator.Put(".xlsx", new WorkbookLoader());
            try
            {
                ExportHelper.ExportToLocal(templatePath, excelPath,
                        new SheetRenderer(ServiceLocalizer["YB0441"].Value,
                            new RepeaterRenderer<SysDeviceDto>("Roster", deviceDtos,
                                new ParameterRenderer<SysDeviceDto>("DeviceNumber", t => t.DeviceNumber),
                                new ParameterRenderer<SysDeviceDto>("CustomerCompanyName", t => t.CustomerCompanyName),
                                new ParameterRenderer<SysDeviceDto>("IsActive", t => t.IsActive == true ? ServiceLocalizer["YB0442"].Value : ServiceLocalizer["YB0443"].Value),
                                new ParameterRenderer<SysDeviceDto>("DeviceNO", t => t.DeviceNO),
                                new ParameterRenderer<SysDeviceDto>("DeviceDateOfProduction", t => t.DeviceDateOfProduction?.ToString("yyyy-MM-dd HH:mm:ss")),
                                new ParameterRenderer<SysDeviceDto>("ScannerNumber", t => t.ScannerNumber),
                                new ParameterRenderer<SysDeviceDto>("ComputerNumber", t => t.ComputerNumber),
                                new ParameterRenderer<SysDeviceDto>("EncryptedDogNumber", t => t.EncryptedDogNumber),
                                new ParameterRenderer<SysDeviceDto>("DeviceUserName", t => t.DeviceUserName),
                                new ParameterRenderer<SysDeviceDto>("DeviceExpire", t => t.DeviceExpire + ServiceLocalizer["YB0444"].Value)
                                )
                            )
                        );
            }
            catch (Exception e)
            {
                Utility.Logger.Error("生成进度Excel异常", e);
                throw e;
            }

            #endregion 生成EXCEL

            return excelPath.Substring(uploadFileOptions.ParentDir.Length);
        }

        private static List<int> ValidYear = new List<int>() { 1, 3, 5 };

        public static bool IsValidYear(int i)
        {
            if (ValidYear.Contains(i))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 设备excel导入
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        public async Task<bool> ImportExcelFile(IFormFile formFile)
        {
            string existedMsg = string.Empty;
            var excelDirectory = "";
            var FilePath = "";
            var errorString = "";
            var HaveErrorDeviceNumber = new List<string>();
            try
            {
                if (formFile.Length == 0)
                    throw new OperationException(ServiceLocalizer["YB0007"].Value);

                using (var stream = formFile.OpenReadStream())
                {
                    excelDirectory = Path.Combine(uploadFileOptions.ParentDir, uploadFileOptions.DeviceExcelDir);
                    if (!Directory.Exists(excelDirectory)) Directory.CreateDirectory(excelDirectory);
                    FilePath = Path.Combine(excelDirectory, Guid.NewGuid() + Path.GetExtension(formFile.FileName));
                    using (FileStream fileStream = new FileStream(FilePath, FileMode.Create))
                    {
                        formFile.CopyTo(fileStream);
                    }
                }

                if (!File.Exists(FilePath))
                {
                    throw new OperationException(string.Format(ServiceLocalizer["YB0176"].Value, FilePath));
                }

                //解析excel
                var excelTable = ExcelHelper.ReadToDataTable(FilePath);
                if (excelTable.Rows.Count == 0)
                {
                    throw new OperationException(ServiceLocalizer["ServiceResource"].Value);
                }

                int rowIndex = 0;
                var entityList = new List<SysDevice>();
                foreach (DataRow row in excelTable.Rows)
                {
                    rowIndex++;
                    string preText = ServiceLocalizer["YB0290"].Value;
                    //数据检查
                    if (string.IsNullOrEmpty(row["产品序列号"].ToString()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0232"].Value);
                    }

                    if (string.IsNullOrEmpty(row["客户单位/名称"].ToString().Trim()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0233"].Value);
                    }

                    if (string.IsNullOrEmpty(row["出厂日期"].ToString()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0234"].Value);
                    }

                    //if (string.IsNullOrEmpty(row["设备软件版本号"].ToString().Trim()))
                    //{
                    //    throw new Exception(preText + "设备软件版本号不能为空");
                    //}

                    if (string.IsNullOrEmpty(row["联系方式"].ToString().Trim()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0235"].Value);
                    }

                    if (!string.IsNullOrEmpty(row["联系方式"].ToString()))
                    {
                        if (!RegChecker.IsMobilePhone(row["联系方式"].ToString()))
                        {
                            throw new OperationException(preText + ServiceLocalizer["YB0295"].Value);
                        }
                    }

                    if (string.IsNullOrEmpty(row["三脚架规格/型号"].ToString().Trim()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0240"].Value);
                    }

                    if (string.IsNullOrEmpty(row["计算机编号"].ToString().Trim()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0241"].Value);
                    }

                    if (string.IsNullOrEmpty(row["计算机规格/型号"].ToString().Trim()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0242"].Value);
                    }

                    if (string.IsNullOrEmpty(row["扫描仪编号"].ToString().Trim()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0243"].Value);
                    }

                    if (string.IsNullOrEmpty(row["扫描仪规格/型号"].ToString().Trim()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0244"].Value);
                    }

                    if (string.IsNullOrEmpty(row["加密狗编号"].ToString()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0302"].Value);
                    }

                    if (string.IsNullOrEmpty(row["加密狗规格/型号"].ToString()))
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0304"].Value);
                    }

                    var entity = new SysDevice();
                    entity.DeviceGuid = Guid.NewGuid();
                    //entity.DeviceSoftwareVersion = row["设备软件版本号"].ToString().Trim();
                    entity.DeviceNumber = row["产品序列号"].ToString().Trim();
                    //客户名称
                    entity.CustomerCompanyName = row["客户单位/名称"].ToString().Trim();
                    //计算机编号
                    entity.ComputerNumber = row["计算机编号"].ToString().Trim();
                    entity.ComputerSystemVersion = "";
                    entity.ComputerType = row["计算机规格/型号"].ToString().Trim();
                    DateTime dateOfProduction;
                    if (DateTime.TryParse(row["出厂日期"].ToString(), out dateOfProduction))
                    {
                        entity.DeviceDateOfProduction = dateOfProduction;
                    }
                    else
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0305"].Value);
                    }

                    int computerExpire;
                    if (int.TryParse(row["计算机保修期"].ToString().Trim().Replace("年", ""), out computerExpire))
                    {
                        if (IsValidYear(computerExpire))
                        {
                            entity.ComputerExpire = computerExpire;
                        }
                        else
                        {
                            throw new OperationException(preText + ServiceLocalizer["YB0307"].Value);
                        }
                    }
                    else
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0308"].Value);
                    }

                    entity.ScannerNumber = row["扫描仪编号"].ToString().Trim();
                    entity.ScannerType = row["扫描仪规格/型号"].ToString().Trim();
                    // ScannerDateOfProduction = Convert.ToDateTime(row["出厂日期"]),

                    int scannerExpire;
                    if (int.TryParse(row["扫描仪保修期"].ToString().Trim().Replace("年", ""), out scannerExpire))
                    {
                        if (IsValidYear(scannerExpire))
                        {
                            entity.ScannerExpire = scannerExpire;
                        }
                        else
                        {
                            throw new OperationException(preText + ServiceLocalizer["YB0310"].Value);
                        }
                    }
                    else
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0311"].Value);
                    }

                    entity.EncryptedDogNumber = row["加密狗编号"].ToString().Trim();
                    entity.EncryptedDogType = row["加密狗规格/型号"].ToString().Trim();

                    int deviceExpire;
                    if (int.TryParse(row["整机保修期"].ToString().Trim().Replace("年", ""), out deviceExpire))
                    {
                        if (IsValidYear(deviceExpire))
                        {
                            entity.DeviceExpire = deviceExpire;
                        }
                        else
                        {
                            throw new OperationException(preText + ServiceLocalizer["YB0313"].Value);
                        }
                    }
                    else
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0314"].Value);
                    }

                    int tripodExpire;
                    if (int.TryParse(row["三脚架保修期"].ToString().Trim().Replace("年", ""), out tripodExpire))
                    {
                        if (IsValidYear(tripodExpire))
                        {
                            entity.TripodExpire = tripodExpire;
                        }
                        else
                        {
                            throw new OperationException(preText + ServiceLocalizer["YB0316"].Value);
                        }
                    }
                    else
                    {
                        throw new OperationException(preText + ServiceLocalizer["YB0317"].Value);
                    }

                    entity.TripodType = row["三脚架规格/型号"].ToString().Trim();
                    entity.CustomerPhoneNumber = row["联系方式"].ToString().Trim();
                    //激活状态
                    entity.IsActive = false;
                    entity.CreatedDate = DateTime.Now;
                    entity.LastUpdatedDate = DateTime.Now;
                    entity.LastUpdatedBy = OperatorProvider.Get()?.YunUserGuid ?? Guid.Empty;
                    entity.CreatedBy = OperatorProvider.Get()?.YunUserGuid ?? Guid.Empty;
                    entity.RowIndex = rowIndex;

                    //检查是否重复数据
                    var flag = await SysDeviceRepository.GetDevice(entity);

                    if (flag.Result == null)
                    {
                        entityList.Add(entity);
                    }
                    else
                    {
                        throw new OperationException(flag.Message);
                    }
                }

                if (entityList.Count > 0)
                {
                    //检查Excel中的数据是否重复
                    for (int i = 0; i < entityList.Count; i++)
                    {
                        var t1 = entityList[i];
                        for (int j = i + 1; j < entityList.Count; j++)
                        {
                            var t2 = entityList[j];
                            if (t1.EncryptedDogType == t2.EncryptedDogType && t1.EncryptedDogNumber == t2.EncryptedDogNumber)
                            {
                                throw new OperationException(string.Format(ServiceLocalizer["YB0318"].Value, t1.RowIndex, t2.RowIndex));
                            }

                            if (t1.DeviceNumber == t2.DeviceNumber)
                            {
                                throw new OperationException(string.Format(ServiceLocalizer["YB0319"].Value, t1.RowIndex, t2.RowIndex));
                            }

                            if (t1.ComputerNumber == t2.ComputerNumber && t1.ComputerType == t2.ComputerType)
                            {
                                throw new OperationException(string.Format(ServiceLocalizer["YB0320"].Value, t1.RowIndex, t2.RowIndex));
                            }

                            if (t1.ScannerNumber == t2.ScannerNumber && t1.ScannerType == t2.ScannerType)
                            {
                                throw new OperationException(string.Format(ServiceLocalizer["YB0321"].Value, t1.RowIndex, t2.RowIndex));
                            }
                        }
                    }

                    SysDeviceRepository.AddRange(entityList);

                    if (HaveErrorDeviceNumber.Count() > 0)
                    {
                        errorString = ServiceLocalizer["YB0322"].Value + string.Join(';', HaveErrorDeviceNumber.ToArray());
                        throw new OperationException(errorString);
                    }

                    if (await UnitOfWork.SaveChangesAsync() > 0)
                    {
                        return true;
                    }
                }
                else
                {
                    throw new OperationException(ServiceLocalizer["YB0323"].Value + existedMsg);
                }
            }
            finally
            {
                if (File.Exists(FilePath))
                {
                    File.Delete(FilePath);
                }
            }
            return false;
        }

        /// <summary>
        /// 把设备设置为激活
        /// </summary>
        /// <param name="deviceEntity"></param>
        /// <param name="userGuid"></param>
        public async Task SetDeviceActive(SysDevice deviceEntity, Guid userGuid)
        {
            deviceEntity.IsActive = true;
            deviceEntity.ActiveDate = DateTime.Now;
            deviceEntity.ActiveUserGuid = userGuid;
            SysDeviceRepository.Update(deviceEntity, i => new { i.IsActive, i.ActiveDate, i.ActiveUserGuid });

            await PushDeviceQueueMessage(deviceEntity.DeviceGuid);
        }

        /// <summary>
        /// 推送设备的队列消息
        /// </summary>
        /// <param name="deviceId"></param>
        public async Task PushDeviceQueueMessage(Guid deviceId)
        {
            await RabbitMQProducer.SendAsync(new MsDevicePushDto
            {
                Type = 1,
                DeviceId = deviceId
            });
        }

        /// <summary>
        /// 作者：黄钧航
        /// 获取所有已激活设备
        /// </summary>
        /// <returns></returns>
        public async Task<List<SysDeviceDtoPart>> GetAllActivedDevices()
        {
            return await SysDeviceRepository.GetAllActivedDevices();
        }

        /// <summary>
        /// 获取某个公司所有已激活的设备
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<List<SysOrgDevicesDto>> GetOrgAllActivedDevices(string orgId)
        {
            List<SysOrgDevicesDto> devices = new List<SysOrgDevicesDto>();
            var list = await SysDeviceRepository.WhereAsync(p => p.SysOrgId == orgId && p.IsActive && !p.IsDeleted);
            list.ForEach(p =>
            {
                devices.Add(new SysOrgDevicesDto
                {
                    DeviceGuid = p.DeviceGuid,
                    EncryptedDogNumber = p.EncryptedDogNumber,
                    SysOrgId = p.SysOrgId
                });
            });

            return devices;
        }

        /// <summary>
        /// 获取某个已激活的设备
        /// </summary>
        /// <param name="usbKeyNo">加密狗编号</param>
        /// <returns></returns>
        public async Task<SysOrgDevicesDto> GetOrgDeviceDetail(string usbKeyNo)
        {
            var device = await SysDeviceRepository.FirstOrDefaultAsync(p => p.EncryptedDogNumber == usbKeyNo && p.IsActive && !p.IsDeleted);

            return device == null ? null : new SysOrgDevicesDto
            {
                DeviceGuid = device.DeviceGuid,
                EncryptedDogNumber = device.EncryptedDogNumber,
                SysOrgId = device.SysOrgId
            };
        }
    }
}